<?php
namespace MTxEntity\DAL\Entity\Repository;
use Doctrine\ORM\EntityRepository;
use MTxEntity;

class UsersRepository extends EntityRepository{

	/**
	 * Get List user
	 * 
	 * @author Thien Le
	 * 
	 * @return array $rst
	 */
	public function getList()
	{
		$rst = array();
		try {
			$qb = $this->getEntityManager()->createQueryBuilder();
			$qb->select('u')
               ->from('MTxEntity:Users', 'u');
               
			$query = $qb->getQuery();
			$rst = $query->getResult();
		} catch (Exception $ex) {
			throw $ex;
		}
		return $rst;	
	}
	
	public function getDataFromView()
	{
		//$q = "SELECT * FROM myview";
		//$rsm = new \Doctrine\ORM\Query\ResultSetMapping;
		//$rsm->addEntityResult('MTxEntity:Users', 'u');
	    //$rsm->addFieldResult('u');
	    //$rsm->addFieldResult('u', 'username', 'username');
	    //$rsm->addMetaResult('u', 'idGroup', 'idGroup');
	    
	    //$rsm->addJoinedEntityResult('MTxEntity:Group', 'g', 'u', 'idGroup');
	    //$rsm->addFieldResult('g', 'idGroup', 'id');
	    //$rsm->addFieldResult('g', 'name', 'name');
	    
		$q = "SELECT * FROM myview";
		$rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
		$rsm->addRootEntityFromClassMetadata('MTxEntity:Users', 'u');
	    $rsm->addMetaResult('u', 'idGroup', 'idGroup');
	    $query = $this->getEntityManager()->createNativeQuery($q, $rsm);
	    $rst = $query->getResult();
	    
	    foreach ($rst as $r) {
	    	echo "<pre> PASSWORD : ";
	    	print_r($r->getPassword());
	    	echo "<pre> USERNAME : ";
	    	print_r($r->getUsername());
	    	echo "<pre> GROUP ID : ";
	    	print_r($r->getIdGroup()->getId());
	    	echo "<pre> GROUP NAME : ";
	    	print_r($r->getIdGroup()->getName());
	    	
	    	echo "<pre> GROUP PARENT ID : ";
	    	print_r($r->getIdGroup()->getIdParent()->getId());
	    	echo "<pre> GROUP PARENT NAME : ";
	    	print_r($r->getIdGroup()->getIdParent()->getGroupParentName());
	    	
	    }
	    return $rst;
	}
	
	public function findById($idUser = '')
	{
		return $this->find('MTxEntity:Users', $idUser);
	}
}